//
//  ZCSPlayMusicViewController.m
//  聆听FM
//
//  Created by dllo on 16/6/14.
//  Copyright © 2016年 Dark. All rights reserved.
//

#import "ZCSPlayMusicViewController.h"
#import "ZCSListenListListModel.h"
#import "TBCircularSlider.h"
#import "ZCSPlayModel.h"
#import <AVFoundation/AVFoundation.h>
#import "AudioPlayerManager.h"
#import "LTPlayListView.h"
#import "LTVoiceModel.h"
#import "LTDataBase.h"
#import "PCSEQVisualizer.h"
#import "LTArchiverTools.h"
#import "LTLastMusicModel.h"


@interface ZCSPlayMusicViewController ()<LTPlayProtocol>
@property (nonatomic, strong) LTPlayListView *playListView;

@property(nonatomic, retain) UIImageView *backImageView;
@property (nonatomic, retain) UIImageView *smallImageView;

@property(nonatomic,weak) UILabel *customLab;

@property(nonatomic,strong) UIView *viewAnima; //装滚动视图的容器
/**
 *  播放按钮
 */
@property (nonatomic, retain) UIButton *playButton;
/**
 *  播放列表按钮
 */
@property (nonatomic, retain) UIButton *menuButton;
/**
 *  模式按钮
 */
@property (nonatomic, retain) UIButton *typeButton;

//上一曲按钮
@property (nonatomic, retain) UIButton *lastButton;

//下一曲按钮
@property (nonatomic, retain) UIButton *nextButton;

//进度条
@property (nonatomic, retain) UISlider *slider;

//左侧时间
@property (nonatomic, retain) UILabel *leftLabel;

//右侧时间
@property (nonatomic, retain) UILabel *rightLabel;

@property (nonatomic, retain) ZCSPlayModel *playModel;

//定时器
@property (nonatomic, retain) NSTimer *imageTimer;

//播放type
@property (nonatomic, assign) PlayMode type;

//标题定时器
@property (nonatomic, retain) NSTimer *titleTimer;

@property (nonatomic, retain) NSTimer *timeTimer;
//初始时间
@property (nonatomic, assign) NSInteger initTime;

@property (nonatomic, assign) CGFloat schedule;

@property (nonatomic, retain) AudioPlayerManager *playerManager;

@property (nonatomic, retain) UIView *playListBackView;
//当前页码
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, retain) LTVoiceModel *voiceModel;

@property (nonatomic, assign) NSInteger onAlbumId;

@property (nonatomic, strong) PCSEQVisualizer *soundPilar;

@property (nonatomic, strong) LTLastMusicModel *lastModel;
@end
static ZCSPlayMusicViewController *playerVC = nil;
@implementation ZCSPlayMusicViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.playerManager = [AudioPlayerManager shareAudioPlayerManager];
        
    }
    return self;
}

+ (ZCSPlayMusicViewController *)sharePlayVC
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playerVC = [[ZCSPlayMusicViewController alloc] init];
    });
    return playerVC;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatView];
    playerVC.view = self.view;
    self.page = 1;
    
    if (!self.dataArray) {
        NSDictionary *dic = [LTArchiverTools unarchiverObjectByKey:@"lastMusic" WithPath:@"lastMusic.plist"];
        if (dic) {
            _lastModel = [[LTLastMusicModel alloc] initWithDic:dic];
            
            if (_lastModel.isRadio == 0) {
                self.dataArray = self.lastModel.dataArray;
                self.musicIndex = self.lastModel.musicIndex;
                self.maxPage = self.lastModel.maxPage;
                self.key = self.lastModel.key;
                self.uid = self.lastModel.uid;
                self.albumId = self.lastModel.albumId;
            }
            else
            {
                self.dataArray = self.lastModel.dataArray;
                self.musicIndex = self.lastModel.musicIndex;
                self.isRadio = YES;
            }
            
        }
    }
   
}


- (void)viewWillAppear:(BOOL)animated
{
    if (self.onDataArray == self.dataArray) {
        self.onDataArray = self.dataArray;
        NSLog(@"同一个专辑");
        if (self.onIndex == self.musicIndex) {
            self.onIndex = self.musicIndex;
            NSLog(@"同一首歌");
        }
        else
        {
            NSLog(@"不是同一首歌");
            [self.imageTimer invalidate];
            [self.timeTimer invalidate];
            [self.titleTimer invalidate];
            [self.playButton setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:1] forState:UIControlStateNormal];
            self.playButton.tag = 10000;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:nil];
            self.playListView.dataArray = self.dataArray;
            self.onIndex = self.musicIndex;
            self.playListView.onDid = self.musicIndex;
            [self.playListView.tableView reloadData];
            [self getDataWithArray:self.dataArray musicIndex:_musicIndex];
        }
    }
    else
    {
        NSLog(@"不是同一个专辑");
        self.page = 1;
        [self.imageTimer invalidate];
        [self.timeTimer invalidate];
        [self.titleTimer invalidate];
        [self.playButton setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:1] forState:UIControlStateNormal];
        self.playButton.tag = 10000;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:nil];
        self.onIndex = self.musicIndex;
        self.onDataArray = self.dataArray;
        self.playListView.dataArray = self.dataArray;
        self.playListView.onDid = self.musicIndex;
        [self.playListView.tableView reloadData];
        [self.playListView.tableView.mj_footer beginRefreshing];
        [self getDataWithArray:self.dataArray musicIndex:_musicIndex];
    }
}
//加载
- (void)getMoreData
{
    
    self.page++;
    if (self.page > self.maxPage) {
        [self.playListView.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    else
    {
        if ([self.key isEqualToString:@""]) {
            [self getMoreDataWith:self.albumId page:self.page];
        }
        else if (self.uid != 0)
        {
            [self getMoreAnchorDataWith:self.uid page:self.page];
        }
        else
        {
            [self getMoreDataWithKey:self.key page:self.page];
        }
        
    }
}

- (void)getMoreDataWithKey:(NSString *)key page:(NSInteger)page
{
    NSString *urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v2/rankingList/track?device=iPhone&key=%@&pageId=%ld&pageSize=20&scale=3", key, page];
    __weak ZCSPlayMusicViewController *pmvc = self;
    [LTNetTool GetNetWithURL:urlString Body:nil Header:nil Response:0 Success:^(id result) {
        for (NSDictionary *dic in result[@"list"]) {
            ZCSListenListListModel *model = [[ZCSListenListListModel alloc] initWithDic:dic];
            [pmvc.dataArray addObject:model];
        }
        pmvc.playListView.dataArray = pmvc.dataArray;
        [pmvc.playListView.tableView reloadData];
        [pmvc.playListView.tableView.mj_footer endRefreshing];
        [pmvc.playListView.tableView.mj_header endRefreshing];
        
    } Failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
    
}

- (void)getMoreAnchorDataWith:(NSInteger)uid page:(NSInteger)page
{
    NSString *urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/v1/artist/tracks?device=android&pageId=%ld&toUid=%ld&track_base_url=http://mobile.ximalaya.com/mobile/v1/artist/tracks", page, uid];
     __weak ZCSPlayMusicViewController *pmvc = self;
   [LTNetTool GetNetWithURL:urlString Body:nil Header:nil Response:0 Success:^(id result) {
       NSArray *tempArray = result[@"list"];
       for (NSDictionary *dic in tempArray) {
           ZCSListenListListModel *model = [[ZCSListenListListModel alloc] initWithDic:dic];
           [pmvc.dataArray addObject:model];
       }
       pmvc.playListView.dataArray = pmvc.dataArray;
       [pmvc.playListView.tableView reloadData];
       [pmvc.playListView.tableView.mj_footer endRefreshing];
   } Failure:^(NSError *error) {
       NSLog(@"%@", error);
   }];
    
}



- (void)getMoreDataWith:(NSInteger)albumId page:(NSInteger)page
{
    NSString *urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/v1/album/track?albumId=%ld&device=iPhone&isAsc=true&pageId=%ld&pageSize=20", albumId, page];
    __weak ZCSPlayMusicViewController *pmvc = self;
    [LTNetTool GetNetWithURL:urlString Body:nil Header:nil Response:0 Success:^(id result) {
        for (NSDictionary *dic in result[@"data"][@"list"]) {
            ZCSListenListListModel *model = [[ZCSListenListListModel alloc] initWithDic:dic];
            [pmvc.dataArray addObject:model];
        }
        pmvc.playListView.dataArray = pmvc.dataArray;
        [pmvc.playListView.tableView reloadData];
        [pmvc.playListView.tableView.mj_footer endRefreshing];

    } Failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)showPlayView
{
    self.typeButton.hidden = NO;
    self.lastButton.hidden = NO;
    self.nextButton.hidden = NO;
    self.menuButton.hidden = NO;
    self.slider.hidden = NO;
    self.leftLabel.hidden = NO;
    self.rightLabel.hidden = NO;
    self.playButton.hidden = NO;
    [self.soundPilar stop];
    self.soundPilar.hidden = YES;
}

- (void)hiddenPlayView
{
    self.typeButton.hidden = YES;
    self.lastButton.hidden = YES;
    self.nextButton.hidden = YES;
    self.menuButton.hidden = YES;
    self.slider.hidden = YES;
    self.leftLabel.hidden = YES;
    self.rightLabel.hidden = YES;
    self.playButton.hidden = YES;
    self.soundPilar.hidden = NO;
    [self.soundPilar start];
}

- (void)setInfoInRadioWith:(LJLRadioPageModel *)model
{
    LTDataBase *data = [LTDataBase shareLTDataBaseTool];
    NSInteger num = [data isSaveDataInTableWithModel_id:model.radioId type:2];
    if (num == 1) {
        [data insertDataWithRadioModel:model];
    }
    
    [self.backImageView sd_setImageWithURL:[NSURL URLWithString:model.radioCoverLarge] placeholderImage:[UIImage sd_animatedGIFNamed:@"占位图"]];
    [self.smallImageView sd_setImageWithURL:[NSURL URLWithString:model.radioCoverLarge] placeholderImage:[UIImage sd_animatedGIFNamed:@"占位图"]];
    self.customLab.text = model.rname;
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
    CGRect newRect = [model.rname boundingRectWithSize:CGSizeMake(10000, 30 * FITHEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    self.customLab.frame = CGRectMake(self.viewAnima.frame.size.width, (self.viewAnima.frame.size.height - 30 * FITHEIGHT) / 2, newRect.size.width + 10, newRect.size.height);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:model.radioCoverLarge];
    [self.playerManager stop];
    [self.playerManager playerPlayWithUrl:model.playUrl];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld", self.musicIndex] , @"musicIndex",self.dataArray, @"dataArray",[NSString stringWithFormat:@"%ld", self.maxPage] , @"maxPage", @"1", @"isRadio",self.key, @"key", [NSString stringWithFormat:@"%ld", self.albumId], @"albumId", [NSString stringWithFormat:@"%ld", self.uid], @"uid",nil];
    [LTArchiverTools archiverObject:dict ByKey:@"lastMusic" WithPath:@"lastMusic.plist"];
    [[NSUserDefaults standardUserDefaults] setObject:model.radioCoverLarge forKey:@"photo"];
    
}

- (void)getDataWithArray:(NSArray *)dataArray musicIndex:(NSInteger)index
{
    if (self.isRadio == YES) {
        [self hiddenPlayView];
        LJLRadioPageModel *model = [dataArray objectAtIndex:index];
        [self setInfoInRadioWith:model];
        self.imageTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(imageRotate) userInfo:nil repeats:YES];
        self.titleTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                           target:self selector:@selector(changePos)
                                                         userInfo:nil repeats:YES];
    }
    else
    {
        [self showPlayView];
    ZCSListenListListModel *model = [self.dataArray objectAtIndex:index];
    NSString *urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/v1/track/baseInfo?device=iPhone&trackId=%ld", model.id];
    __weak ZCSPlayMusicViewController *pmvc = self;
    [LTNetTool GetNetWithURL:urlString Body:nil Header:nil Response:0 Success:^(id result) {
        pmvc.voiceModel = [[LTVoiceModel alloc] initWithDic:result];
        pmvc.voiceModel.musicIndex = index;
        pmvc.voiceModel.maxPage = pmvc.maxPage;
        pmvc.playModel = [[ZCSPlayModel alloc] initWithDic:result];
        [pmvc setInfoWithModel:pmvc.playModel];
        pmvc.imageTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(imageRotate) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:pmvc.imageTimer forMode:NSRunLoopCommonModes];
        pmvc.titleTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                           target:self selector:@selector(changePos)
                                                         userInfo:nil repeats:YES];
         [[NSRunLoop currentRunLoop] addTimer:pmvc.titleTimer forMode:NSRunLoopCommonModes];
        pmvc.timeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAndSlider) userInfo:nil repeats:YES];
         [[NSRunLoop currentRunLoop] addTimer:pmvc.timeTimer forMode:NSRunLoopCommonModes];
        pmvc.initTime = 0;
        pmvc.schedule = 0;
    } Failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    }
    
}
- (void)setInfoWithModel:(ZCSPlayModel *)model
{
    self.albumId = model.albumId;
    LTDataBase *data = [LTDataBase shareLTDataBaseTool];
   NSInteger num = [data isSaveDataInTableWithModel_id:self.voiceModel.trackId type:4];
    if (num == 1) {
        if (self.voiceModel.albumId != self.onAlbumId) {
            NSLog(@"不是一个专辑");
           [data insertDataWithSoundModel:self.voiceModel];
        }
        self.onAlbumId = self.voiceModel.albumId;
    }
    [self.backImageView sd_setImageWithURL:[NSURL URLWithString:model.coverLarge] placeholderImage:[UIImage sd_animatedGIFNamed:@"占位图"]];
    [self.smallImageView sd_setImageWithURL:[NSURL URLWithString:model.coverLarge] placeholderImage:[UIImage sd_animatedGIFNamed:@"占位图"]];
    self.rightLabel.text = [self getTimeWith:model.duration];
    self.customLab.text = model.title;
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
    CGRect newRect = [model.title boundingRectWithSize:CGSizeMake(10000, 30 * FITHEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    self.customLab.frame = CGRectMake(self.viewAnima.frame.size.width, (self.viewAnima.frame.size.height - 30 * FITHEIGHT) / 2, newRect.size.width + 10, newRect.size.height);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:model.coverMiddle];
    [self.playerManager stop];
    [self.playerManager playerPlayWithUrl:model.playUrl64];
    self.playListView.onDid = self.musicIndex;
    self.playListView.dataArray = self.dataArray;
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld", self.musicIndex] , @"musicIndex",self.dataArray, @"dataArray",[NSString stringWithFormat:@"%ld", self.maxPage] , @"maxPage", @"0", @"isRadio", self.key, @"key", [NSString stringWithFormat:@"%ld", self.albumId], @"albumId", [NSString stringWithFormat:@"%ld", self.uid], @"uid",nil];
    [LTArchiverTools archiverObject:dict ByKey:@"lastMusic" WithPath:@"lastMusic.plist"];
    [[NSUserDefaults standardUserDefaults] setObject:model.coverLarge forKey:@"photo"];
}

- (void)creatView
{
    self.backImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    self.backImageView.userInteractionEnabled = YES;
    [self.view addSubview:_backImageView];
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:2];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = self.backImageView.frame;
    [self.backImageView addSubview:effectView];
    
    TBCircularSlider *sliderVioce = [[TBCircularSlider alloc]initWithFrame:CGRectMake(0 * FITWIDTH, 80 * FITHEIGHT, TB_SLIDER_SIZE, TB_SLIDER_SIZE)];
    [sliderVioce addTarget:self action:@selector(newValue:) forControlEvents:UIControlEventValueChanged];
    sliderVioce.angle = 180;
    [self.view addSubview:sliderVioce];
    self.smallImageView = [[UIImageView alloc] initWithFrame:CGRectMake(70 * FITWIDTH, 70 * FITHEIGHT, 235 * FITWIDTH, 235 * FITHEIGHT)];
    self.smallImageView.layer.cornerRadius = ( 235 / 2.0 ) * FITHEIGHT;
    self.smallImageView.layer.masksToBounds = YES;
    //self.smallImageView.backgroundColor = [UIColor redColor];
    [sliderVioce addSubview:_smallImageView];
    //模式按钮
    self.typeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.typeButton.frame = CGRectMake(50 * FITWIDTH, self.view.frame.size.height - 140 * FITHEIGHT, 32 * FITWIDTH, 32 * FITHEIGHT);
    [self.typeButton setImage:[[UIImage imageNamed:@"循环播放"]  imageWithRenderingMode:1] forState:UIControlStateNormal];
    self.typeButton.tag = 1000;
    [self.view addSubview:_typeButton];
    
    [self.typeButton addTarget:self action:@selector(didSelectedTypeButton:) forControlEvents:UIControlEventTouchUpInside];
    [self addMiddleTitleView];
    
    //菜单按钮
    self.menuButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.menuButton.frame = CGRectMake(self.view.frame.size.width - 82 * FITWIDTH, self.typeButton.frame.origin.y + 4, 32 * FITWIDTH, 32 * FITHEIGHT);
    [self.menuButton setImage:[[UIImage imageNamed:@"播放列表"]  imageWithRenderingMode:1] forState:UIControlStateNormal];
    [self.view addSubview:_menuButton];
    
    [self.menuButton addTarget:self action:@selector(didSelectMenuButton:) forControlEvents:UIControlEventTouchUpInside];
    
    //上一曲
    
    self.lastButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.lastButton.frame = CGRectMake(112 * FITWIDTH, self.typeButton.frame.origin.y, 32 * FITWIDTH, 32 * FITHEIGHT);
    [self.lastButton setImage:[[UIImage imageNamed:@"lastMusic"]  imageWithRenderingMode:1] forState:UIControlStateNormal];
    [self.view addSubview:_lastButton];
    
    [self.lastButton addTarget:self action:@selector(didSelectedLastMusicButton:) forControlEvents:UIControlEventTouchUpInside];
    //下一曲
    
    self.nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.nextButton.frame = CGRectMake(self.menuButton.frame.origin.x - 62 * FITWIDTH, self.typeButton.frame.origin.y, 32 * FITWIDTH, 32 * FITHEIGHT);
    [self.nextButton setImage:[[UIImage imageNamed:@"nextMusic"]  imageWithRenderingMode:1] forState:UIControlStateNormal];
    [self.view addSubview:_nextButton];
    
    [self.nextButton addTarget:self action:@selector(didSelectNextMusicButton:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.playButton setImage:[[UIImage imageNamed:@"pause"]  imageWithRenderingMode:1] forState:UIControlStateNormal];
    self.playButton.frame = CGRectMake(self.lastButton.frame.origin.x + self.lastButton.frame.size.width + 18 * FITWIDTH, self.lastButton.frame.origin.y - 10 * FITHEIGHT, 50 * FITWIDTH, 50 * FITHEIGHT);
    [self.view addSubview:_playButton];
    [self.playButton addTarget:self action:@selector(didSelectPlayButton:) forControlEvents:UIControlEventTouchUpInside];
    self.playButton.tag = 10000;
    
    
    
    //进度条
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(50 * FITWIDTH, sliderVioce.frame.origin.y + sliderVioce.frame.size.height + 10 * FITHEIGHT, 275 * FITWIDTH, 20 * FITHEIGHT)];
    self.slider.minimumValue = 0;
    self.slider.maximumValue = 1;
    self.slider.minimumTrackTintColor = [UIColor colorWithRed:0.94 green:0.70 blue:0.21 alpha:1.00];
    [self.slider setThumbImage:[UIImage imageNamed:@"slider-default-handle"] forState:UIControlStateNormal];
    [self.view addSubview:_slider];
    
    [self.slider addTarget:self action:@selector(didSlideSlider:) forControlEvents:UIControlEventValueChanged];
    
    //左侧时间
    self.leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 * FITWIDTH, self.slider.frame.origin.y + 5 * FITHEIGHT, 40 * FITWIDTH, 10 * FITHEIGHT)];
    self.leftLabel.font = [UIFont systemFontOfSize:12];
    self.leftLabel.textAlignment = 1;
    self.leftLabel.textColor = [UIColor whiteColor];
    self.initTime = 0;
    self.leftLabel.text = [self getTimeWith:self.initTime];
    [self.view addSubview:_leftLabel];
    
    //右侧时间
    self.rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 50 * FITWIDTH, self.slider.frame.origin.y + 5 * FITHEIGHT, 40 * FITWIDTH, 10 * FITHEIGHT)];
    self.rightLabel.font = [UIFont systemFontOfSize:12];
    self.rightLabel.textAlignment = 1;
    self.rightLabel.text = @"--:--";
    self.rightLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:_rightLabel];
    
    self.soundPilar = [[PCSEQVisualizer alloc] initWithNumberOfBars:25];
    CGRect frame = self.soundPilar.frame;
    //self.soundPilar.backgroundColor = [UIColor redColor];
    frame.origin.x = 25 * FITWIDTH;
    frame.origin.y = 450 * FITHEIGHT;
    self.soundPilar.frame = frame;
    [self.view addSubview:_soundPilar];
    //[self.soundPilar start];
    //返回图片
    UIImageView *backToImage = [[UIImageView alloc] initWithFrame:CGRectMake(20, 29, 32, 32)];
    backToImage.userInteractionEnabled = YES;
    backToImage.image = [UIImage imageNamed:@"downBack"];
    [self.view addSubview:backToImage];
    UITapGestureRecognizer *backToTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backToLastView)];
    [backToImage addGestureRecognizer:backToTap];
    
    self.playListBackView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.playListBackView.backgroundColor = [UIColor blackColor];
    self.playListBackView.alpha = 0.3;
    self.playListBackView.hidden = YES;
    [self.view addSubview:_playListBackView];
    
    UITapGestureRecognizer *backTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didSelectPlay:)];
    [self.playListBackView addGestureRecognizer:backTap];
    
    
    //播放列表
    self.playListView = [[LTPlayListView alloc] initWithFrame:CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, SCREENHEIGHT - 200 * FITHEIGHT)];
    self.playListView.delegata = self;
    __weak ZCSPlayMusicViewController *weakSelf = self;
    self.playListView.playListBlock = ^(NSInteger index)
    {
        weakSelf.musicIndex = index;
        [weakSelf.imageTimer invalidate];
        [weakSelf.titleTimer invalidate];
        [weakSelf.timeTimer invalidate];
        [weakSelf getDataWithArray:weakSelf.dataArray musicIndex:index];
    };
    
    self.playListView.downView.close = ^(void)
    {
        [UIView animateWithDuration:0.5 animations:^{
            weakSelf.playListBackView.hidden = YES;
            weakSelf.playListView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, SCREENHEIGHT - 200 * FITHEIGHT);
        }];
    };
    [self.view addSubview:_playListView];
}
#pragma mark -- 返回
- (void)didSelectPlay:(UITapGestureRecognizer *)tap
{
    [UIView animateWithDuration:0.5 animations:^{
        self.playListBackView.hidden = YES;
        self.playListView.frame = CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, SCREENHEIGHT - 200 * FITHEIGHT);
    }];
    
}


- (NSString *)getTimeWith:(NSInteger)num
{
    NSString *minString = [NSString stringWithFormat:@"%02ld", num / 60];
    NSString *second = [NSString stringWithFormat:@"%02ld", num % 60];
    return  [NSString stringWithFormat:@"%@:%@", minString, second];
}

#pragma mark -- 时间和进度条
- (void)timeAndSlider
{
    self.initTime++;
    if (_initTime >= self.playModel.duration) {
        
        switch (_type) {
                //顺序
            case 0:
                [self didSelectNextMusicButton:self.nextButton];
                break;
            case 1:
                [self.timeTimer invalidate];
                [self.imageTimer invalidate];
                [self.titleTimer invalidate];
                NSLog(@"这一曲的%ld", self.musicIndex);
                [self getDataWithArray:self.dataArray musicIndex:self.musicIndex];
                break;
            case 2:
                [self didSelectNextMusicButton:self.nextButton];
                break;
            default:
                break;
        }
    }
    self.leftLabel.text = [self getTimeWith:self.initTime];
    self.schedule += 1.0 / self.playModel.duration;
    if (self.schedule == 1.0) {
        _schedule = 0;
    }
    self.slider.value = _schedule;
}


//添加中间视图
-(void) addMiddleTitleView
{
    //定义视图大小
    CGFloat viewX = (self.view.frame.size.width-200 * FITWIDTH)/2;
    UIView *viewAnima = [[UIView alloc] initWithFrame:CGRectMake(viewX, 50 , SCREENWIDTH, 40)];
    viewAnima.backgroundColor = [UIColor  clearColor];
    self.viewAnima = viewAnima;
    //定义视图容器
    [self.view addSubview:viewAnima];
    CGFloat customLabY = (self.viewAnima.frame.size.height - 30 * FITHEIGHT)/2;
    UILabel *customLab = [[UILabel alloc] init];
    customLab.frame = CGRectMake(self.viewAnima.frame.size.width, customLabY, 600, 30);
    //[customLab sizeToFit];
    [customLab setTextColor:[UIColor whiteColor]];
    customLab.font = [UIFont boldSystemFontOfSize:16];
    self.customLab = customLab;
    //添加视图
    [self.viewAnima addSubview:customLab];
}
- (void)changePos
{
    CGPoint curPos = self.customLab.center;
    
    // 当curPos的x坐标已经超过了屏幕的宽度
    if(curPos.x < -100)
    {
        CGFloat jianJu = self.customLab.frame.size.width/2;
        // 控制蝴蝶再次从屏幕左侧开始移动
        self.customLab.center = CGPointMake(self.viewAnima.frame.size.width + jianJu, 20);
    }
    else
    {
        // 通过修改iv的center属性来改变iv控件的位置
        self.customLab.center = CGPointMake(curPos.x - 4, 20);
    }
    //其实蝴蝶的整个移动都是————靠iv.center来去设置的
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.key = @"";
    self.isRadio = NO;
    self.uid = 0;
}

#pragma mark -- 图片旋转
- (void)imageRotate
{
    self.smallImageView.transform = CGAffineTransformRotate(self.smallImageView.transform, M_PI / 180);
}

#pragma mark -- 模式按钮
- (void)didSelectedTypeButton:(UIButton *)sender
{
    NSInteger num = sender.tag - 1000;
    switch (num) {
        case 0:
            [self.typeButton setImage:[[UIImage imageNamed:@"单曲循环"] imageWithRenderingMode:1] forState:UIControlStateNormal];
            self.typeButton.tag = 1001;
            self.type = 1;
            [MBProgressHUD showSuccess:@"单曲循环"];
            break;
        case 1:
            [self.typeButton setImage:[[UIImage imageNamed:@"随机播放"] imageWithRenderingMode:1] forState:UIControlStateNormal];
            [MBProgressHUD showSuccess:@"随机播放"];
            self.type = 2;
            self.typeButton.tag = 1002;
            break;
        case 2:
            [self.typeButton setImage:[[UIImage imageNamed:@"循环播放"] imageWithRenderingMode:1]forState:UIControlStateNormal];
            [MBProgressHUD showSuccess:@"循环播放"];
            self.type = 0;
            self.typeButton.tag = 1000;
            break;
        default:
            break;
    }
    
    
}

#pragma mark -- 上一曲
- (void)didSelectedLastMusicButton:(UIButton *)sender
{
    if (self.type != 2) {
        self.musicIndex -= 1;
        if (self.musicIndex < 0) {
            self.musicIndex = 0;
            [MBProgressHUD showSuccess:@"已经是第一首了"];
        }
    }
    else
    {
        self.musicIndex = arc4random() % self.dataArray.count;
    }
    
    [self.imageTimer invalidate];
    [self.playButton setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:1]forState:UIControlStateNormal];
    self.playButton.tag = 10000;
    [self.titleTimer invalidate];
    CGFloat customLabY = (self.viewAnima.frame.size.height - 30 * FITHEIGHT)/2;
    self.customLab.frame = CGRectMake(self.viewAnima.frame.size.width, customLabY, 400, 30);
    [self.timeTimer invalidate];
    self.initTime = 0;
    self.schedule = 0;
    NSLog(@"上一曲的%ld", self.musicIndex);
    self.playListView.onDid = self.musicIndex;
    [self.playListView.tableView reloadData];
    [self getDataWithArray:self.dataArray musicIndex:self.musicIndex];
    
}
#pragma mark -- 下一曲
- (void)didSelectNextMusicButton:(UIButton *)sender
{
    if (self.type == 0 || self.type == 1) {
        self.musicIndex += 1;
        if (self.musicIndex > self.dataArray.count - 1) {
            self.musicIndex = self.dataArray.count - 1;
            [MBProgressHUD showSuccess:@"已经到最后一首了"];
        }
    }
    else
    {
        self.musicIndex = arc4random() % self.dataArray.count;
    }
    
    [self.imageTimer invalidate];
    [self.timeTimer invalidate];
    [self.titleTimer invalidate];
    [self.playButton setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:1]forState:UIControlStateNormal];
    self.playButton.tag = 10000;
    CGFloat customLabY = (self.viewAnima.frame.size.height - 30 * FITHEIGHT)/2;
    self.customLab.frame = CGRectMake(self.viewAnima.frame.size.width, customLabY, 375, 30);
    NSLog(@"下一曲的%ld", self.musicIndex);
    self.playListView.onDid = self.musicIndex;
    [self.playListView.tableView reloadData];
    [self getDataWithArray:self.dataArray musicIndex:self.musicIndex];
    
}

#pragma mark -- 播放按钮
- (void)didSelectPlayButton:(UIButton *)sender
{
    if (self.playButton.tag == 10000) {
        [self.playButton setImage:[[UIImage imageNamed:@"play1"] imageWithRenderingMode:1]forState:UIControlStateNormal];
        self.playButton.tag = 10001;
        [self.playerManager pause];
        [self.imageTimer invalidate];
        [self.titleTimer invalidate];
        [self.timeTimer invalidate];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pause" object:nil];
        
    }
    else
    {
        [self.playerManager play];
        [self.playButton setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:1]forState:UIControlStateNormal];
        self.playButton.tag = 10000;
        self.imageTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(imageRotate) userInfo:nil repeats:YES];
        self.titleTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                           target:self selector:@selector(changePos)
                                                         userInfo:nil repeats:YES];
        self.timeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAndSlider) userInfo:nil repeats:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:nil];
        
    }
}

#pragma mark -- 菜单
- (void)didSelectMenuButton:(UIButton *)sender
{
    
    [UIView animateWithDuration:0.5 animations:^{
        self.playListBackView.hidden = NO;
        self.playListView.frame = CGRectMake(0, 200 * FITHEIGHT, SCREENWIDTH, SCREENHEIGHT - 200 * FITHEIGHT);
    }];
    
}



#pragma mark -- 音量调节
-(void)newValue:(TBCircularSlider*)slider{
    
    if (slider.angle > 300) {
        //[MBProgressHUD showSuccess:@"声音太大了,小心耳朵哦~"];
     
    }
    self.playerManager.volume = slider.angle / 360.0;
}

#pragma mark --滑块控件触发方法:
- (void)didSlideSlider:(UISlider *)sender
{
    [self.timeTimer invalidate];
    self.initTime = sender.value * self.playModel.duration;
    self.leftLabel.text = [self getTimeWith:self.initTime];
    self.schedule = (sender.value * self.playModel.duration) / self.playModel.duration;
    [self.playerManager pause];
    
    
    //播放
    if (self.playButton.tag == 10001) {
        
        [self.playerManager seekToTime:CMTimeMakeWithSeconds(self.initTime, self.playerManager.currentTime.timescale) completionHandler:^(BOOL finished) {
            [self.playerManager pause];
            
        }];
        
    }
    else
    {
        self.timeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAndSlider) userInfo:nil repeats:YES];
        [self.playerManager seekToTime:CMTimeMakeWithSeconds(self.initTime, self.playerManager.currentTime.timescale) completionHandler:^(BOOL finished) {
            
            [self.playerManager play];
            
            
        }];
    }
    
    
}
#pragma mark -- 返回
- (void)backToLastView
{
    [self dismissViewControllerAnimated:YES completion:nil];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
